﻿using System.Linq;
using Castle.DynamicProxy;

namespace Framework.Core
{
    public static class ProxyInterceptors
    {
        public static T Get<T>(this object o)
        {
            var proxyTargetAccessor = o as IProxyTargetAccessor;

            if (proxyTargetAccessor == null)
            {
                throw new ProxyException(string.Format("this is not a {0}", typeof(T).FullName));
            }

            var interceptor = proxyTargetAccessor.GetInterceptors().FirstOrDefault(x => x is T);

            if (interceptor == null)
            {
                throw new ProxyException(string.Format("this is not a {0}", typeof(T).FullName));
            }

            return (T)interceptor;
        }
    }
}
